﻿/*
 * Created by SharpDevelop.
 * User: ley
 * Date: 5/16/2010
 * Time: 8:45 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;

namespace Ley.Common.Validation
{
	public class Validator<TSubject>
	{
		private IDictionary<string, IValidationRuleSet<TSubject>> _rules;
		
		public TSubject Subject { get; protected set; }
		
		public int RuleCount
		{
			get
			{
				return _rules.Count;
			}
		}
		
		public Validator(TSubject subject)
		{
			_rules = new Dictionary<string, IValidationRuleSet<TSubject>>();
			
			Subject = subject;
		}
		
		public ValidationRuleSet<TSubject, TProperty> Check<TProperty>(Expression<Func<TSubject, TProperty>> propertyRule)
		{
			if (!_rules.ContainsKey(propertyRule.ToString()))
			{
			    _rules.Add(propertyRule.ToString(), new ValidationRuleSet<TSubject, TProperty>(this, propertyRule));
			}
			    
			return _rules[propertyRule.ToString()] as ValidationRuleSet<TSubject, TProperty>;
		}
		
		public ValidationResult PerformValidation()
		{
			var result = new ValidationResult();
			
			foreach (var ruleset in _rules.Values)
			{
				var message = ruleset.Execute();
				if (!string.IsNullOrEmpty(message))
					result.AddValidationMessage(message);
			}
			
			return result;
		}
	}
}
